package it.cqupt.web.controller.store;

import com.github.pagehelper.PageInfo;
import it.cqupt.domain.store.Catalog;
import it.cqupt.domain.store.Company;
import it.cqupt.domain.store.Question;
import it.cqupt.utils.BeanUtil;
import it.cqupt.web.controller.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@WebServlet("/store/question")
public class QuestionServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter("operation");
        if("list".equals(operation)){
            this.list(req,resp);
        }else if("toAdd".equals(operation)){
            this.toAdd(req,resp);
        }else if("save".equals(operation)){
            try {
                this.save(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if("toEdit".equals(operation)){
            this.toEdit(req,resp);
        }else if("edit".equals(operation)){
            try {
                this.edit(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if("delete".equals(operation)){
            this.delete(req,resp);
        }else if("toTestFileUpload".equals(operation)){
            this.toTestFileUpload(req,resp);
        }else if("testUpload".equals(operation)){
            try {
                this.testUpload(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if("downloadReport".equals(operation)){
            this.downloadReport(req,resp);
        }
    }

    private void downloadReport(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ByteArrayOutputStream outputStream = questionService.downloadReport();
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("题目报表.xlsx".getBytes(),"iso8859-1");
        resp.addHeader("Content-Disposition","attachment;filename="+fileName);
        ServletOutputStream sos = resp.getOutputStream();
        outputStream.writeTo(sos);
        sos.flush();
        sos.close();
        outputStream.close();
    }

    private void toTestFileUpload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/pages/store/question/testFileUpload.jsp").forward(req,resp);
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Question question = BeanUtil.fillBean(req, Question.class);
        questionService.delete(question);
        resp.sendRedirect(req.getContextPath()+"/store/question?operation=list");
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        if(ServletFileUpload.isMultipartContent(req)){
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            boolean flag = false;
            for(FileItem item : fileItems){
                if(StringUtils.isNotBlank(item.getName())){
                    flag = true;
                    break;
                }
            }
            Question question = BeanUtil.fillBean(fileItems, Question.class);
            questionService.update(question,flag);
            if(flag){
                for(FileItem item : fileItems){
                    if(!item.isFormField()){
                        item.write(new File(this.getServletContext().getRealPath("upload"),question.getPicture()));
                    }
                }
            }
            resp.sendRedirect(req.getContextPath()+"/store/question?operation=list");
        }
    }

    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Question question = questionService.findById(id);
        List<Company> companyList = cs.findAll();
        List<Catalog> catalogList = catalogService.findAll();
        req.setAttribute("question",question);
        req.setAttribute("companyList",companyList);
        req.setAttribute("catalogList",catalogList);
        req.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(req,resp);
    }
    private void testUpload(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        if(ServletFileUpload.isMultipartContent(req)){
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            for(FileItem item : fileItems){
                if(!item.isFormField()){
                    item.write(new File(this.getServletContext().getRealPath("upload"),item.getName()));
                }
            }
        }
    }
    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        if(ServletFileUpload.isMultipartContent(req)){
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            boolean flag = false;
            for(FileItem item : fileItems){
                if(StringUtils.isNotBlank(item.getName())){
                    flag = true;
                    break;
                }
            }
            Question question = BeanUtil.fillBean(fileItems, Question.class);
            String picture = questionService.save(question,flag);
            if(flag){
                for(FileItem item : fileItems){
                    if(!item.isFormField()){
                        item.write(new File(this.getServletContext().getRealPath("upload"),picture));
                    }
                }
            }
            resp.sendRedirect(req.getContextPath()+"/store/question?operation=list");
        }
    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Company> companyList = cs.findAll();
        List<Catalog> catalogList = catalogService.findAll();
        req.setAttribute("companyList",companyList);
        req.setAttribute("catalogList",catalogList);
        req.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(req,resp);
    }
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int page = 1;
        int size = 5;
        if(StringUtils.isNotBlank(req.getParameter("page"))){
            page = Integer.parseInt(req.getParameter("page"));
        }
        if(StringUtils.isNotBlank(req.getParameter("size"))){
            size = Integer.parseInt(req.getParameter("size"));
        }
        PageInfo all = questionService.findAll(page, size);
        req.setAttribute("page",all);
        req.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
